import { FN, httpConfig } from "@Tea/model";
import { useElMessageBox, UseElMessageBoxType,useGloablLoading } from "../hooks";
import { AxiosError } from "axios";
import { InitHttpReturnType } from "./http";

export type initRouterType = {
  onIdentityFail: FN
}

export const isSuccessCode = (code: number) => httpConfig.successCode.includes(code)
export const isFailCode = (code: number) => !isSuccessCode(code)

export const responseError = (initConfig: initRouterType, AxiosError: AxiosError) => {
  const { closeLoading } = useGloablLoading()
  const { response } = AxiosError as unknown as {
    response: {
      status: number
      data: InitHttpReturnType<any>
    }
  }

  const config: UseElMessageBoxType = {
    content: "",
    type: "error",
  }

  console.log(response);
  switch (response?.status) {
    case 401:
      config.content = response.data.msg
      config.finallyCallback = () => {

        // 身份失效
        initConfig.onIdentityFail()
      }
      break;
    case 404:
      config.content = "服务地址有误"
      break;
    case 500:
      config.content = response.data.msg
      break;
    default:
      config.content = '未定义状态码 ' + response.data.code
      console.log('未知错误---', AxiosError);
      break;
  }

  closeLoading()
  
  useElMessageBox(config)
}